﻿using FarPoint.Web.Spread;
using FarPoint.Web.Spread.Model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ControlExplorer.samples.OrderEntry
{
  public partial class Cart : System.Web.UI.Page
  {
    DefaultSheetDataModel model;
    DefaultSheetStyleModel fpstylemodel;
    StyleInfo style = new StyleInfo();
    int intcnt;


    private void Page_Load(System.Object sender, System.EventArgs e)
    {
      //Put user code to initialize the page here

      if (!Information.IsArray(Session["cart"]))
      {
        lbNoMatch.Text = "There are no items in your cart.";
        lbNoMatch.Visible = true;
        FpSpread1.Visible = false;
        return;
      }
      this.FpSpread1.UseClipboard = false;

      //InitSpread()

      //Showing cart done in Page_PreRender event

      if (this.InIE9PlusCompatView())
      {
        foreach (FarPoint.Web.Spread.FpSpread spread in this.GetSpreads(this))
        {
          FarPoint.Web.Spread.SheetView activeSheet = spread.ActiveSheetView;
          FarPoint.Web.Spread.Border border = activeSheet.DefaultStyle.Border;
          if (border == null || border.IsEmpty)
          {
            activeSheet.DefaultStyle.Border = new FarPoint.Web.Spread.Border(BorderStyle.Solid, activeSheet.GridLineColor, 1);
          }
        }
      }

    }

    private bool InIE9PlusCompatView()
    {
      if (this.Page.Request.Browser.MajorVersion == 7)
      {
        string userAgent = this.Page.Request.UserAgent;
        int index = userAgent.IndexOf("trident/", StringComparison.OrdinalIgnoreCase);
        int index2 = 0;
        if (index >= 0)
        {
          index2 = userAgent.IndexOf(";", index);
        }
        else
        {
          index2 = -1;
        }
        if (index2 > index && index >= 0)
        {
          double tridentVersion = 0;
          if (double.TryParse(userAgent.Substring(index + 8, index2 - (index + 8)), out tridentVersion))
          {
            return tridentVersion >= 5;
          }
        }
      }
      return false;
    }

    private System.Collections.IEnumerable GetSpreads(Control ctrl)
    {
      System.Collections.Generic.List<FarPoint.Web.Spread.FpSpread> list = new System.Collections.Generic.List<FarPoint.Web.Spread.FpSpread>();
      foreach (Control c in ctrl.Controls)
      {
        foreach (FarPoint.Web.Spread.FpSpread spread in GetSpreads(c))
        {
          list.Add(spread);
        }

        if (c is FarPoint.Web.Spread.FpSpread)
        {
          list.Add((FarPoint.Web.Spread.FpSpread)c);
        }
      }

      return list;
    }


    public void InitSpread()
    {
      //Disble View State
      FpSpread1.EnableViewState = false;

      model = new DefaultSheetDataModel(intcnt, 5);
      //rows, columns
      fpstylemodel = new DefaultSheetStyleModel(intcnt, 5);
      FpSpread1.HorizontalScrollBarPolicy = ScrollBarPolicy.AsNeeded;
      FpSpread1.Sheets[0].DataModel = model;
      FpSpread1.Sheets[0].PageSize = 10;

      style.Reset();
      style.Font.Size = FontUnit.Point(8);
      style.Font.Name = "Verdana";
      FpSpread1.ActiveSheetView.SetStyleInfo(-1, -1, style);

      //Set Column Labels
      FpSpread1.ActiveSheetView.SetColumnLabel(0, 0, "数量");
      FpSpread1.ActiveSheetView.SetColumnLabel(0, 1, "描述");
      FpSpread1.ActiveSheetView.SetColumnLabel(0, 3, "单价");
      FpSpread1.ActiveSheetView.SetColumnLabel(0, 4, "总额");

      //Merge the Image and Description Header
      FpSpread1.ActiveSheetView.ColumnHeaderSpanModel.Add(0, 1, 1, 2);

      //Set Column Widths
      FpSpread1.ActiveSheetView.SetColumnWidth(1, 75);
      //Book Image
      FpSpread1.ActiveSheetView.SetColumnWidth(2, 225);
      //Description
      FpSpread1.ActiveSheetView.SetColumnWidth(3, 65);
      //Unit Price
      FpSpread1.ActiveSheetView.SetColumnWidth(4, 100);
      //Extended Price

      FpSpread1.ActiveSheetView.ColumnHeader.DefaultStyle.BackColor = Color.DarkSeaGreen;
      FpSpread1.ActiveSheetView.RowHeader.DefaultStyle.BackColor = Color.DarkSeaGreen;
      FpSpread1.ActiveSheetView.SheetCornerStyle.BackColor = Color.DarkSeaGreen;

      FpSpread1.ActiveSheetView.Columns[1, 4].Locked = true;

    }
    public void ShowCart()
    {
      int i = 0;
      decimal extprice = 0;
      decimal unitprice = 0;

      //Cart(i, 0) = Book ID
      //Cart(i, 1) = Title desc
      //Cart(i, 2) = Unit Price
      //Cart(i, 3) = 'Qty
      //Cart(i, 4) = Book Picture ID

      i = 0;
      string[,] sessionCart = (string[,])Session["cart"];
      while (!string.IsNullOrEmpty(sessionCart[i, 0]) & i <= Information.UBound(sessionCart))
      {
        //Get the extended price
        //Price * Qty
        if (Information.IsNumeric(sessionCart[i, 2]) & Information.IsNumeric(sessionCart[i, 3]))
        {
          extprice = decimal.Parse(sessionCart[i, 2]) * decimal.Parse(sessionCart[i, 3]);
          unitprice = decimal.Parse(sessionCart[i, 2]);
        }
        else
        {
          extprice = 0;
          unitprice = 0;
        }

        model.SetValue(i, 0, sessionCart[i, 3]);
        //Qty
        model.SetValue(i, 2, sessionCart[i, 1]);
        //Desc.
        model.SetValue(i, 3, Strings.FormatCurrency(unitprice, 2));
        //Unit Price
        model.SetValue(i, 4, Strings.FormatCurrency(extprice, 2));
        //Extended Price

        //Set up the styles
        //QTY: Integer
        style.Reset();
        style.CellType = new IntegerCellType();
        FpSpread1.ActiveSheetView.SetStyleInfo(i, 0, style);
        FpSpread1.ActiveSheetView.SetColumnWidth(0, 70);

        //Image
        style.Reset();
        style.CellType = new ImageCellType("images/books/book" + sessionCart[i, 4] + ".gif");
        FpSpread1.ActiveSheetView.SetStyleInfo(i, 1, style);

        FpSpread1.ActiveSheetView.SetRowHeight(i, 90);
        //Image Row


        //Description
        style.Reset();
        //style.Locked = False
        //style.Locked = True
        FpSpread1.ActiveSheetView.SetStyleInfo(i, 2, style);

        //PRICE
        style.Reset();
        style.HorizontalAlign = HorizontalAlign.Right;
        //style.Locked = True
        FpSpread1.ActiveSheetView.SetStyleInfo(i, 3, style);
        FpSpread1.ActiveSheetView.SetStyleInfo(i, 4, style);


        i = i + 1;

      }

    }

    private void FpSpread1_UpdateCommand(object sender, FarPoint.Web.Spread.SpreadCommandEventArgs e)
    {
      UpdateCart((int)e.CommandArgument,(int)e.EditValues[0]);
      //rownum, new qty
    }

    public void UpdateCart(int rownum, int newqty)
    {
      //Update the cart
      int i = 0;
      int arycnt = 0;
      int j = 0;
      string[,] tempcart = new string[51, 5];
      string[,] remcart = new string[51, 5];


      if (Information.IsDBNull(newqty))
        newqty = 0;

      //Get the cart
      tempcart = (string[,])Session["cart"];

      //Update the cart
      tempcart[rownum, 3] = newqty.ToString(NumberFormatInfo.InvariantInfo);

      if (newqty == 0)
      {
        //Removing an item.
        //remcart = tempcart
        //Init. Shopping Cart
        for (i = 0; i <= Information.UBound(tempcart); i++)
        {
          remcart[i, 0] = "";
          //ID
          remcart[i, 1] = "";
          //Title desc
          remcart[i, 2] = "0";
          //Unit Price
          remcart[i, 3] = "0";
          //Qty
          remcart[i, 4] = "";
          //Book Picture ID
        }

        i = 0;
        arycnt = 0;
        while (!string.IsNullOrEmpty(tempcart[i, 0]) & i <= Information.UBound(tempcart))
        {
          if (tempcart[i, 3] != "0")
          {
            //Add to new cart
            for (j = 0; j <= 4; j++)
            {
              remcart[arycnt, j] = tempcart[i, j];
            }
            arycnt += 1;
          }
          i += 1;
        }
        tempcart = remcart;
      }

      //Save the new cart
      Session["cart"] = tempcart;

    }


    private void Page_PreRender(object sender, System.EventArgs e)
    {
      if (!Information.IsArray(Session["cart"]))
      {
          lbNoMatch.Text = "购物车为空。";
        lbNoMatch.Visible = true;
        FpSpread1.Visible = false;
        return;
      }

      intcnt = 0;
      //Get the cart count
      string[,] sessionCart = (string[,])Session["cart"];
      while (!string.IsNullOrEmpty(sessionCart[intcnt, 0]) & intcnt <= Information.UBound(sessionCart))
      {
        intcnt += 1;
      }

      if (intcnt == 0)
      {
          lbNoMatch.Text = "购物车为空。";
        lbNoMatch.Visible = true;
        FpSpread1.Visible = false;
        return;
      }

      InitSpread();
      ShowCart();
    }
  }
}